from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from . import magic_services
from apps.magic_models import MagicMockProfit
from apps.magic_models import MagicUser
from fly2018.db_conf import magic_redis
from fly2018.toolkit import jwt_kit
from fly2018.toolkit import db_kit
from django.conf import settings
from django.db.models import Q
from django.forms.models import model_to_dict
import json
import random
import math
from datetime import datetime, timedelta
import csv


def index(request):
    context = {}
    template = loader.get_template('app/login.html')
    return HttpResponse(template.render(context, request))


def render_menu(request):

    is_admin = False
    show_all = False
    if hasattr(request, "username"):
        username = request.username
        if "admin" == username:
            is_admin = True
        user = MagicUser.objects.filter(username=username).first()
        if user.user_permission:
            user_permission = user.user_permission
        else:
            show_all = True
    else:
        return

    if is_admin or show_all:
        return [{"name": "总体收益","url": "adv.html", "icon": "fa fa-home"},
                     {"name": "广告位1日收益", "url": "adv1.html?current=1", "icon": "fa fa-bar-chart-o"},
                     {"name": "广告位2日收益", "url": "adv2.html?current=1", "icon": "fa fa-desktop"},
                     {"name": "广告位1月报表", "url": "adv3.html?current=1", "icon": "fa fa-bar-chart-o"},
                     {"name": "广告位2月报表", "url": "adv4.html?current=1", "icon": "fa fa-desktop"},
                     {"name": "权限设置", "url": "permission.html", "icon": "fa fa fa-edit"},
                     {"name": "数据生成", "url": "fake.html", "icon": "fa fa fa-clone"}]
    else:
        up = json.loads(user_permission)
        menus = [{"name": "总体收益", "url": "adv.html", "icon": "fa fa-home"}]
        if up["adv2"] == "on":
            menus.append({"name": "广告位2日收益", "url": "adv2.html", "icon": "fa fa-desktop"})
        if up["adv1"] == "on":
            menus.append({"name": "广告位1日收益", "url": "adv1.html", "icon": "fa fa-bar-chart-o"})
        if up["adv3"] == "on":
            menus.append({"name": "广告位3月收益", "url": "adv3.html", "icon": "fa fa-bar-chart-o"})
        if up["adv4"] == "on":
            menus.append({"name": "广告位4月收益", "url": "adv4.html", "icon": "fa fa-bar-chart-o"})
        return menus


def gentella_html(request):
    context = {}
    # The template to be loaded as per gentelella.
    # All resource paths for gentelella end in .html.

    # Pick out the html file name from the url. And load that template.
    load_template = request.path.split('/')[-1]

    # 用户信息
    if load_template == "pwd.html" and request.method.lower() == "get":
        username = request.username
        template = loader.get_template('app/' + load_template)
        response = HttpResponse(template.render({"username": username,"menus": render_menu(request)}, request))
        return response

    if load_template == "pwd.html" and request.method.lower() == "post":
        username = request.username
        password = request.POST.get("password")
        template = loader.get_template('app/' + load_template)
        MagicUser.objects.filter(username=username).update(password=password)
        response = HttpResponse(template.render({"username": username,"menus": render_menu(request)}, request))
        return response

    if load_template == "permission.html" and request.method.lower() == "get":
        # 设置权限
        template = loader.get_template('app/' + load_template)
        all_users = MagicUser.objects.filter(~Q(username='admin'))
        all_users = [model_to_dict(user) for user in all_users]
        username = request.username
        self = MagicUser.objects.filter(username=username).first()
        user_permission = self.user_permission
        menus = render_menu(request)
        response = HttpResponse(template.render({"users": all_users, "up": json.loads(user_permission),
                                                 "menus": menus}, request))
        return response

    if load_template == "fake.html" and request.method.lower() == "get":
        # 生成数据
        template = loader.get_template('app/' + load_template)
        all_users = MagicUser.objects.filter(~Q(username='admin'))
        all_users = [model_to_dict(user) for user in all_users]
        username = request.username
        self = MagicUser.objects.filter(username=username).first()
        user_permission = self.user_permission
        menus = render_menu(request)
        response = HttpResponse(template.render({"users": all_users, "up": json.loads(user_permission),
                                                 "menus": menus}, request))
        return response

    if load_template == "fake.html" and request.method.lower() == "post":
        # 生成数据
        i_per_profit = request.POST.get("per_profit")
        i_adv_views = request.POST.get("adv_views")
        i_adv_clicks = request.POST.get("adv_views")
        start_adv_date = request.POST.get("adv_date_start")
        end_adv_date = request.POST.get("adv_date_end")
        adv_id = request.POST.get("adv_id")
        deleted = request.POST.get("deleted")

        dt = datetime.now()
        dt_format = dt.strftime('%Y-%m-%d')
        if not start_adv_date:
            start_adv_date = dt_format
        else:
            start_adv_date = datetime.strptime(start_adv_date, '%m/%d/%Y')

        if not end_adv_date:
            end_adv_date = dt_format
        else:
            end_adv_date = datetime.strptime(end_adv_date, '%m/%d/%Y')

        _delta_days = (end_adv_date - start_adv_date).days
        delta_days = _delta_days
        if _delta_days == 0:
            delta_days = 1

        start_random = 20
        end_random = 50

        for delta_day in range(1, delta_days):
            if i_per_profit:
                try:
                    per_profit = float(i_per_profit)
                except:
                    per_profit = round(random.uniform(start_random, end_random), 2)
            else:
                per_profit = round(random.uniform(start_random, end_random), 2)

            if i_adv_views:
                try:
                    adv_views = int(i_adv_views)
                except:
                    adv_views = int(per_profit * 500)
            else:
                adv_views = int(per_profit * 500)

            if i_adv_clicks:
                try:
                    adv_clicks = int(i_adv_clicks)
                except:
                    adv_clicks = int((adv_views * random.uniform(7, 10)) / 1000)
            else:
                adv_clicks = int((adv_views * random.uniform(7, 10)) / 1000)

            if _delta_days == 0:
                c_time = start_adv_date
            else:
                c_time = start_adv_date + timedelta(days=delta_day)
            c_time_format = c_time.strftime('%Y-%m-%d')
            if deleted:
                MagicMockProfit.objects.filter(adv_date=c_time_format, adv_id=adv_id).delete()
            else:
                mp_results = MagicMockProfit.objects.filter(adv_date=c_time_format, adv_id=adv_id)

                if not mp_results:
                    MagicMockProfit.objects.create(adv_id=adv_id, adv_views=adv_views,
                                                   adv_clicks=adv_clicks, adv_eCPM=2, adv_profit=per_profit,
                                                   adv_date=c_time_format, is_deleted=0,
                                                   create_at=c_time,
                                                   modify_at=c_time
                                                   )
                else:
                    MagicMockProfit.objects.filter(adv_date=c_time_format, adv_id=adv_id).update(
                        adv_views=adv_views, adv_clicks=adv_clicks, adv_profit=per_profit,
                        create_at=c_time, modify_at=c_time)

        template = loader.get_template('app/' + load_template)
        all_users = MagicUser.objects.filter(~Q(username='admin'))
        all_users = [model_to_dict(user) for user in all_users]
        username = request.username
        self = MagicUser.objects.filter(username=username).first()
        user_permission = self.user_permission
        menus = render_menu(request)
        response = HttpResponse(template.render({"users": all_users, "up": json.loads(user_permission),
                                                 "menus": menus}, request))
        return response

    if load_template == "adv1_excel.csv" and request.method.lower() == "get":
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="广告位1收益数据.csv"'
        writer = csv.writer(response)

        profit_results = MagicMockProfit.objects.order_by("-create_at").filter(adv_id='256472',
                                                                               create_at__lte=_today())
        writer.writerow(['日期', '展示数', '点击数', 'eCMP(元)', '当日收益(元)'])
        for pr in profit_results:
            profit_list = [pr.adv_date, pr.adv_views, pr.adv_clicks, pr.adv_eCPM, pr.adv_profit]
            writer.writerow(profit_list)
        return response

    if load_template == "adv2_excel.csv" and request.method.lower() == "get":
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="广告位2收益数据.csv"'
        writer = csv.writer(response)

        profit_results = MagicMockProfit.objects.order_by("-create_at").filter(adv_id='264659',
                                                                               create_at__lte=_today())
        writer.writerow(['日期', '展示数', '点击数', 'eCMP(元)', '当日收益(元)'])
        for pr in profit_results:
            profit_list = [pr.adv_date, pr.adv_views, pr.adv_clicks, pr.adv_eCPM, pr.adv_profit]
            writer.writerow(profit_list)
        return response

    if load_template == "permission.html" and request.method.lower() == "post":
        # 设置权限
        user_id = request.POST.get("user_id")
        adv1 = request.POST.get("adv1", "un")
        adv2 = request.POST.get("adv2", "un")
        adv3 = request.POST.get("adv3", "un")
        adv4 = request.POST.get("adv4", "un")
        up = {"adv1": adv1, "adv2": adv2, "adv3": adv3, "adv4": adv4}
        if user_id == 0 or user_id == "0":
            MagicUser.objects.update(user_permission=json.dumps(up))
        else:
            MagicUser.objects.filter(id=user_id).update(user_permission=json.dumps(up))

        template = loader.get_template('app/' + load_template)
        all_users = MagicUser.objects.filter(~Q(username='admin'))
        all_users = [model_to_dict(user) for user in all_users]
        response = HttpResponse(template.render({"users": all_users, "up": up, "menus": render_menu(request)}, request))
        return response

    if load_template == "login.html" and request.method.lower() == "post":
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username.strip() and password.strip():
            rs = magic_services.login(username, password)
            if rs:
                domain = settings.SESSION_COOKIE_DOMAIN
                response = HttpResponseRedirect('adv.html')
                token = jwt_kit.encode_token(rs.id, username)
                response.set_cookie('token', bytes.decode(token), domain=domain, max_age=60 * 60 * 24 * 30)
                response.set_cookie('username', username, domain=domain, max_age=60 * 60 * 24 * 30)
                return response

    elif load_template == "register.html" and request.method.lower() == "post":
        username = request.POST.get("username")
        password = request.POST.get("password")
        token = request.POST.get("invitation")
        if username and password and token and username != "admin":
            invitation_code = magic_redis.get("invitation")
            if invitation_code or token == "341234":
                MagicUser.objects.create(username=username, password=password)
                load_template = "login.html"
    elif load_template == "adv.html": # 合计
        profit_results = MagicMockProfit.objects.all()
        profit = 0
        for pr in profit_results:
            profit = profit + pr.adv_profit
        yd = _yesterday()
        yesterday_format = yd.strftime('%Y-%m-%d')

        yesterday_results = MagicMockProfit.objects.filter(adv_date=yesterday_format)
        yesterday_profit = 0
        for yr in yesterday_results:
            yesterday_profit = yesterday_profit + yr.adv_profit
        month_format = yd.strftime('%Y-%m')
        month_results = MagicMockProfit.objects.filter(adv_date__contains=month_format)
        month_profit = 0
        for mr in month_results:
            month_profit = month_profit + mr.adv_profit
        context["yesterday_profit"] = round(yesterday_profit, 2)
        context["month_profit"] = round(month_profit, 2)
        context["profit"] = round(profit, 2)
        context["menus"] = render_menu(request)
    elif load_template == "adv1.html":
        # 广告1
        profit_results = MagicMockProfit.objects.order_by("-adv_date").filter(adv_id='256472',
                                                                               create_at__lte=_today())
        profit_list = list()
        profit = 0
        for pr in profit_results:
            profit_list.append({
                "adv_id": "ID:{}".format(pr.adv_id),
                "adv_title": "咪咕阅读APP焦点图",
                "adv_date": pr.adv_date,
                "adv_views": pr.adv_views,
                "adv_clicks": pr.adv_clicks,
                "adv_eCPM": pr.adv_eCPM,
                "adv_profit": pr.adv_profit
            })
            profit = profit + pr.adv_profit
        yd = _yesterday()
        yesterday_format = yd.strftime('%Y-%m-%d')
        yesterday_results = MagicMockProfit.objects.filter(adv_date=yesterday_format, adv_id='256472')
        yesterday_profit = 0
        for yr in yesterday_results:
            yesterday_profit = yr.adv_profit
        month_format = yd.strftime('%Y-%m')
        month_results = MagicMockProfit.objects.filter(adv_date__contains=month_format, adv_id='256472')
        month_profit = 0
        for mr in month_results:
            month_profit = month_profit + mr.adv_profit
        context["yesterday_profit"] = round(yesterday_profit, 2)
        context["month_profit"] = round(month_profit, 2)
        context["profit"] = round(profit, 2)
        current = request.GET.get("current", "1")

        pages = int((len(profit_list) + 15 - 1) / 15)
        context["pages"] = pages
        if int(current) == 1 or pages == 1:
            context["pre_disabled"] = "disabled"
            context["pre_href"] = "javascript:void(0)"
        else:
            context["pre_disabled"] = ""
            context["pre_href"] = "?current="+str(int(current)-1)

        if int(current) == pages or pages == 1:
            context["next_disabled"] = "disabled"
            context["next_href"] = "javascript:void(0)"
        else:
            context["next_disabled"] = ""
            context["next_href"] = "?current=" + str(int(current) + 1)
        context["next"] = int(current) + 1

        context["profit_list"] = profit_list[int(current)*15:15*(int(current)+1)]

        context["menus"] = render_menu(request)

    elif load_template == "adv2.html":
        # 广告2
        profit_results = MagicMockProfit.objects.order_by("-create_at").filter(adv_id='264659',
                                                                               create_at__lte=_today())
        profit_list = list()
        profit = 0
        for pr in profit_results:
            profit_list.append({
                "adv_id": "ID:{}".format(pr.adv_id),
                "adv_title": "新闻H5页面",
                "adv_date": pr.adv_date,
                "adv_views": pr.adv_views,
                "adv_clicks": pr.adv_clicks,
                "adv_eCPM": pr.adv_eCPM,
                "adv_profit": pr.adv_profit
            })
            profit = profit + pr.adv_profit
        yd = _yesterday()
        yesterday_format = yd.strftime('%Y-%m-%d')
        yesterday_results = MagicMockProfit.objects.filter(adv_date=yesterday_format, adv_id='264659')
        yesterday_profit = 0
        for yr in yesterday_results:
            yesterday_profit = yr.adv_profit
        month_format = yd.strftime('%Y-%m')
        month_results = MagicMockProfit.objects.filter(adv_date__contains=month_format, adv_id='264659')
        month_profit = 0
        for mr in month_results:
            month_profit = month_profit + mr.adv_profit
        context["yesterday_profit"] = round(yesterday_profit, 2)
        context["month_profit"] = round(month_profit, 2)
        context["profit"] = round(profit, 2)

        current = request.GET.get("current", "1")

        pages = int((len(profit_list) + 15 - 1) / 15)
        context["pages"] = pages
        if int(current) == 1 or pages == 1:
            context["pre_disabled"] = "disabled"
            context["pre_href"] = "javascript:void(0)"
        else:
            context["pre_disabled"] = ""
            context["pre_href"] = "?current=" + str(int(current) - 1)

        if int(current) == pages or pages == 1:
            context["next_disabled"] = "disabled"
            context["next_href"] = "javascript:void(0)"
        else:
            context["next_disabled"] = ""
            context["next_href"] = "?current=" + str(int(current) + 1)
        context["next"] = int(current) + 1

        context["profit_list"] = profit_list[int(current) * 15:15 * (int(current) + 1)]

        context["menus"] = render_menu(request)
    elif load_template == "adv3.html":
        # 广告1- 月
        # profit_results = MagicMockProfit.objects.order_by("-create_at").filter(adv_id='264659',
        #                                                                        create_at__lte=_today())

        month_sql = "select sum(adv_profit) as 'profit'," \
                    "sum(adv_views) as 'views' , " \
                    "sum(adv_clicks) as 'clicks', " \
                    "date_format(adv_date, '%Y年%m月') as 'month' " \
                    "from magic_mock_profit where adv_id='256472' group by date_format(adv_date, '%Y年%m月')"

        profit_results = db_kit.fetch_all(month_sql)

        profit_list = list()
        profit = 0
        for pr in profit_results:
            profit_list.append({
                "adv_profit": round(pr[0], 2),
                "adv_views": pr[1],
                "adv_clicks": pr[2],
                "adv_month": pr[3]
            })
        context["profit_list"] = profit_list
        context["menus"] = render_menu(request)
    elif load_template == "adv4.html":
        # 广告2 - 月
        # profit_results = MagicMockProfit.objects.order_by("-create_at").filter(adv_id='264659',
        #                                                                        create_at__lte=_today())

        month_sql = "select sum(adv_profit) as 'profit'," \
                    "sum(adv_views) as 'views' , " \
                    "sum(adv_clicks) as 'clicks', " \
                    "date_format(adv_date, '%Y年%m月') as 'month' " \
                    "from magic_mock_profit where adv_id='264659' group by date_format(adv_date, '%Y年%m月')"

        profit_results = db_kit.fetch_all(month_sql)

        profit_list = list()
        profit = 0
        for pr in profit_results:
            profit_list.append({
                "adv_profit": round(pr[0], 2),
                "adv_views": pr[1],
                "adv_clicks": pr[2],
                "adv_month": pr[3]
            })
        context["profit_list"] = profit_list
        context["menus"] = render_menu(request)

    template = loader.get_template('app/' + load_template)
    if hasattr(request, "username"):
        context["username"] = request.username
    response = HttpResponse(template.render(context, request))
    return response


def _yesterday():
    import datetime
    today = datetime.date.today()
    one_day = datetime.timedelta(days=1)
    yesterday = today - one_day
    return yesterday


def _today():
    import datetime
    today = datetime.date.today()
    td = today.strftime('%Y-%m-%d')
    dt = datetime.datetime.strptime(td, '%Y-%m-%d')
    return dt
